package com.example.buildtable.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaJoinQueryWrapper;
import com.example.buildtable.pojo.User;
import com.example.common.util.R;
import com.example.buildtable.pojo.LoginLog;
import com.example.buildtable.service.LoginLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@Tag(name = "登录日志")
@RequestMapping(value = "/loginLog/")
public class LoginLogController {
    @Autowired
    private LoginLogService loginLogService;
    
    @Operation(summary = "查询所有登录日志数据")
    @GetMapping(value = "/getAllLoginLog")
    public R getAllLoginLog() {
        LambdaJoinQueryWrapper<LoginLog> wrapper = new LambdaJoinQueryWrapper<>(LoginLog.class);
        wrapper.innerJoin(User.class, User::getUserId, LoginLog::getOperUserId);
        List<LoginLog> loginLogList = loginLogService.list(wrapper);
        return R.ok("查询所有登录日志数据成功").data("loginLogList", loginLogList);
    }
    
    @Operation(summary = "增加登录日志")
    @PostMapping(value = "/addLoginLog")
    public R addLoginLog(LoginLog loginLog) {
        boolean flag = loginLogService.save(loginLog);
        if (flag) {
            return R.ok("增加登录日志成功");
        } else {
            return R.ok("增加登录日志失败");
        }
    }

    @Operation(summary = "删除登录日志")
    @GetMapping(value = "/deleteLoginLog/{loginId}")
    public R deleteLoginLog(@PathVariable("loginId") Integer loginId) {
        boolean flag = loginLogService.removeById(loginId);
        if (flag) {
            return R.ok("删除登录日志成功");
        } else {
            return R.ok("删除登录日志失败");
        }
    }

    @Operation(summary = "按照登录日志查看")
    @GetMapping(value = "/getLoginLogById/{loginId}")
    public R getLoginLogById(@PathVariable("loginId") Integer loginId) {
        LambdaJoinQueryWrapper<LoginLog> wrapper = new LambdaJoinQueryWrapper<>(LoginLog.class);
        wrapper.innerJoin(User.class, User::getUserId, LoginLog::getOperUserId);
        wrapper.eq(LoginLog::getLoginId, loginId);
        LoginLog loginLog = loginLogService.getOne(wrapper);
        if (loginLog != null) {
            return R.ok("按照登录日志查看成功").data("loginLog", loginLog);
        } else {
            return R.error("按照登录日志查看失败");
        }
    }

    @Operation(summary = "修改登录日志")
    @PostMapping(value = "/updateLoginLog")
    public R updateLoginLog(LoginLog loginLog) {
        boolean flag = loginLogService.updateById(loginLog);
        if (flag) {
            return R.ok("修改登录日志成功");
        } else {
            return R.ok("修改登录日志失败");
        }
    }
}